"""
仪表盘相关API路由
"""

import logging
from datetime import datetime, timedelta
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, or_

from ...core.database import get_db
from ...core.security import get_current_user, get_current_admin_user
from ...models.user import User
from ...models.analysis import AnalysisRecord
from ...models.requirement import Requirement
from ...models.test_case import TestCase, ExecutionRecord
from ...models.api_automation import ApiInterface, TestScenario, ScenarioExecution
from ...models.ui_automation import UiAutomationScript, UiAutomationExecution

router = APIRouter()
logger = logging.getLogger(__name__)


@router.get("/stats")
async def get_dashboard_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取仪表盘统计数据"""
    try:
        # 根据用户权限决定数据范围
        if current_user.is_admin:
            # 管理员可以看到所有数据
            user_filter = None
        else:
            # 普通用户只能看到自己的数据
            user_filter = current_user.id

        # 需求分析次数（只统计requirement_analysis类型）
        analysis_query = db.query(AnalysisRecord).filter(AnalysisRecord.analysis_type == "requirement_analysis")
        if user_filter:
            analysis_query = analysis_query.filter(AnalysisRecord.user_id == user_filter)
        total_analysis = analysis_query.count()

        # 测试用例生成次数
        test_case_generation_query = db.query(AnalysisRecord).filter(AnalysisRecord.analysis_type == "test_case_generation")
        if user_filter:
            test_case_generation_query = test_case_generation_query.filter(AnalysisRecord.user_id == user_filter)
        total_test_case_generation = test_case_generation_query.count()

        # 生成测试用例数量
        try:
            test_cases_query = db.query(TestCase)
            if user_filter:
                # 检查字段是否存在，如果不存在则跳过过滤
                test_cases_query = test_cases_query.filter(TestCase.created_by == user_filter)
            total_test_cases = test_cases_query.count()
        except Exception as e:
            logger.warning(f"TestCase.created_by字段不存在，使用全部数据: {e}")
            total_test_cases = db.query(TestCase).count()

        # 需求项目数量
        requirements_query = db.query(Requirement)
        if user_filter:
            requirements_query = requirements_query.filter(Requirement.creator_id == user_filter)
        total_requirements = requirements_query.count()

        # UI脚本数量
        try:
            ui_scripts_query = db.query(UiAutomationScript)
            if user_filter:
                ui_scripts_query = ui_scripts_query.filter(UiAutomationScript.created_by == user_filter)
            total_ui_scripts = ui_scripts_query.count()
        except Exception as e:
            logger.warning(f"UiAutomationScript查询失败: {e}")
            total_ui_scripts = 0

        # API接口数量
        try:
            api_interfaces_query = db.query(ApiInterface)
            if user_filter:
                api_interfaces_query = api_interfaces_query.filter(ApiInterface.created_by == user_filter)
            total_api_interfaces = api_interfaces_query.count()
        except Exception as e:
            logger.warning(f"ApiInterface查询失败: {e}")
            total_api_interfaces = 0

        # 测试场景数量
        try:
            scenarios_query = db.query(TestScenario)
            if user_filter:
                scenarios_query = scenarios_query.filter(TestScenario.created_by == user_filter)
            total_scenarios = scenarios_query.count()
        except Exception as e:
            logger.warning(f"TestScenario查询失败: {e}")
            total_scenarios = 0

        # UI执行次数
        try:
            ui_executions_query = db.query(UiAutomationExecution)
            if user_filter:
                ui_executions_query = ui_executions_query.filter(UiAutomationExecution.executed_by == user_filter)
            total_ui_executions = ui_executions_query.count()
        except Exception as e:
            logger.warning(f"UiAutomationExecution查询失败: {e}")
            total_ui_executions = 0

        # API场景执行次数
        try:
            scenario_executions_query = db.query(ScenarioExecution)
            if user_filter:
                scenario_executions_query = scenario_executions_query.filter(ScenarioExecution.executor_id == user_filter)
            total_scenario_executions = scenario_executions_query.count()
        except Exception as e:
            logger.warning(f"ScenarioExecution查询失败: {e}")
            total_scenario_executions = 0

        # 处理文件数量（从分析记录中统计）
        file_analysis_query = db.query(AnalysisRecord).filter(AnalysisRecord.file_name.isnot(None))
        if user_filter:
            file_analysis_query = file_analysis_query.filter(AnalysisRecord.user_id == user_filter)
        total_files = file_analysis_query.count()

        return {
            "success": True,
            "data": {
                "totalAnalysis": total_analysis,
                "totalTestCaseGeneration": total_test_case_generation,
                "totalTestCases": total_test_cases,
                "totalRequirements": total_requirements,
                "totalFiles": total_files,
                "totalUiScripts": total_ui_scripts,
                "totalApiInterfaces": total_api_interfaces,
                "totalScenarios": total_scenarios,
                "totalUiExecutions": total_ui_executions,
                "totalScenarioExecutions": total_scenario_executions,
                "userRole": "admin" if current_user.is_admin else "user",
                "username": current_user.username
            }
        }
        
    except Exception as e:
        logger.error(f"获取仪表盘统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取统计数据失败")


@router.get("/activities")
async def get_recent_activities(
    limit: int = Query(10, description="活动数量限制"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取最近活动列表"""
    try:
        activities = []
        
        # 根据用户权限决定数据范围
        if current_user.is_admin:
            user_filter = None
        else:
            user_filter = current_user.id

        # 最近的需求分析活动
        analysis_query = db.query(AnalysisRecord).filter(
            AnalysisRecord.status == "success",
            AnalysisRecord.analysis_type == "requirement_analysis"
        )
        if user_filter:
            analysis_query = analysis_query.filter(AnalysisRecord.user_id == user_filter)
        
        recent_analysis = analysis_query.order_by(AnalysisRecord.created_at.desc()).limit(limit // 4).all()
        for record in recent_analysis:
            activities.append({
                "id": f"analysis_{record.id}",
                "title": f"完成需求分析: {record.file_name or '文本输入'}",
                "time": record.created_at,
                "type": "analysis",
                "icon": "TrendCharts",
                "color": "#409EFF"
            })

        # 最近的测试用例生成活动
        test_case_gen_query = db.query(AnalysisRecord).filter(
            AnalysisRecord.status == "success",
            AnalysisRecord.analysis_type == "test_case_generation"
        )
        if user_filter:
            test_case_gen_query = test_case_gen_query.filter(AnalysisRecord.user_id == user_filter)
        
        recent_test_case_gen = test_case_gen_query.order_by(AnalysisRecord.created_at.desc()).limit(limit // 4).all()
        for record in recent_test_case_gen:
            activities.append({
                "id": f"test_case_gen_{record.id}",
                "title": f"生成测试用例: {record.file_name or '文本输入'}",
                "time": record.created_at,
                "type": "test_case_generation",
                "icon": "DocumentAdd",
                "color": "#67C23A"
            })

        # 最近的测试用例创建活动
        try:
            test_cases_query = db.query(TestCase)
            if user_filter:
                test_cases_query = test_cases_query.filter(TestCase.created_by == user_filter)
            
            recent_test_cases = test_cases_query.order_by(TestCase.created_at.desc()).limit(limit // 4).all()
            for test_case in recent_test_cases:
                activities.append({
                    "id": f"testcase_{test_case.id}",
                    "title": f"创建测试用例: {test_case.title}",
                    "time": test_case.created_at,
                    "type": "testcase",
                    "icon": "List",
                    "color": "#67C23A"
                })
        except Exception as e:
            logger.warning(f"获取测试用例活动失败，字段可能不存在: {e}")
            # 跳过测试用例活动

        # 最近的UI脚本执行活动
        try:
            ui_executions_query = db.query(UiAutomationExecution)
            if user_filter:
                ui_executions_query = ui_executions_query.filter(UiAutomationExecution.executed_by == user_filter)
            
            recent_ui_executions = ui_executions_query.order_by(UiAutomationExecution.created_at.desc()).limit(limit // 4).all()
            for execution in recent_ui_executions:
                status_color = "#67C23A" if execution.status.value == "success" else "#F56C6C"
                activities.append({
                    "id": f"ui_execution_{execution.id}",
                    "title": f"UI脚本执行: {execution.script_name or execution.execution_name}",
                    "time": execution.created_at,
                    "type": "ui_execution",
                    "icon": "Monitor",
                    "color": status_color
                })
        except Exception as e:
            logger.warning(f"获取UI执行活动失败: {e}")

        # 最近的API场景执行活动
        try:
            scenario_executions_query = db.query(ScenarioExecution)
            if user_filter:
                scenario_executions_query = scenario_executions_query.filter(ScenarioExecution.executor_id == user_filter)
            
            recent_scenario_executions = scenario_executions_query.order_by(ScenarioExecution.created_at.desc()).limit(limit // 4).all()
            for execution in recent_scenario_executions:
                status_color = "#67C23A" if execution.status == "completed" else "#F56C6C"
                activities.append({
                    "id": f"scenario_execution_{execution.id}",
                    "title": f"API场景执行: {execution.execution_id}",
                    "time": execution.created_at,
                    "type": "scenario_execution",
                    "icon": "Connection",
                    "color": status_color
                })
        except Exception as e:
            logger.warning(f"获取API场景执行活动失败: {e}")

        # 按时间排序并限制数量
        activities.sort(key=lambda x: x["time"], reverse=True)
        activities = activities[:limit]

        return {
            "success": True,
            "data": {
                "items": activities,
                "total": len(activities)
            }
        }
        
    except Exception as e:
        logger.error(f"获取最近活动失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取最近活动失败")


@router.get("/charts/{chart_type}")
async def get_chart_data(
    chart_type: str,
    days: int = Query(30, description="统计天数"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取图表数据"""
    try:
        # 计算时间范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        # 根据用户权限决定数据范围
        if current_user.is_admin:
            user_filter = None
        else:
            user_filter = current_user.id

        if chart_type == "analysis_trend":
            # 需求分析趋势
            query = db.query(
                func.date(AnalysisRecord.created_at).label('date'),
                func.count(AnalysisRecord.id).label('count')
            ).filter(
                AnalysisRecord.created_at >= start_date,
                AnalysisRecord.created_at <= end_date
            )
            
            if user_filter:
                query = query.filter(AnalysisRecord.user_id == user_filter)
            
            results = query.group_by(func.date(AnalysisRecord.created_at)).all()
            
            data = [{"date": str(result.date), "count": result.count} for result in results]
            
        elif chart_type == "execution_status":
            # 执行状态分布
            ui_exec_query = db.query(
                UiAutomationExecution.status.label('status'),
                func.count(UiAutomationExecution.id).label('count')
            )
            
            if user_filter:
                ui_exec_query = ui_exec_query.filter(UiAutomationExecution.executed_by == user_filter)
            
            ui_results = ui_exec_query.group_by(UiAutomationExecution.status).all()
            
            data = [{"status": result.status.value, "count": result.count, "type": "UI"} for result in ui_results]
            
        elif chart_type == "user_activity":
            # 仅管理员可以查看用户活动统计
            if not current_user.is_admin:
                raise HTTPException(status_code=403, detail="权限不足")
            
            # 用户活动统计
            analysis_stats = db.query(
                User.username,
                func.count(AnalysisRecord.id).label('analysis_count')
            ).outerjoin(AnalysisRecord).group_by(User.id, User.username).all()
            
            data = [{"username": stat.username, "analysis_count": stat.analysis_count} for stat in analysis_stats]
            
        else:
            raise HTTPException(status_code=400, detail="不支持的图表类型")

        return {
            "success": True,
            "data": {
                "chart_type": chart_type,
                "data": data,
                "date_range": {
                    "start": start_date.isoformat(),
                    "end": end_date.isoformat()
                }
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取图表数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取图表数据失败")


@router.get("/admin/user-stats")
async def get_user_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户统计数据（仅管理员）"""
    try:
        # 检查管理员权限
        if not current_user.is_admin:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="需要管理员权限"
            )
        # 查询每个用户的统计数据
        users = db.query(User).filter(User.is_active == True).all()
        
        user_stats = []
        for user in users:
            # 统计各项数据
            analysis_count = db.query(AnalysisRecord).filter(
                AnalysisRecord.user_id == user.id,
                AnalysisRecord.analysis_type == "requirement_analysis"
            ).count()
            test_case_generation_count = db.query(AnalysisRecord).filter(
                AnalysisRecord.user_id == user.id,
                AnalysisRecord.analysis_type == "test_case_generation"
            ).count()
            requirements_count = db.query(Requirement).filter(Requirement.creator_id == user.id).count()
            
            # 处理可能缺失的字段
            try:
                test_cases_count = db.query(TestCase).filter(TestCase.created_by == user.id).count()
            except Exception:
                test_cases_count = 0
                
            try:
                ui_scripts_count = db.query(UiAutomationScript).filter(UiAutomationScript.created_by == user.id).count()
            except Exception:
                ui_scripts_count = 0
                
            try:
                api_interfaces_count = db.query(ApiInterface).filter(ApiInterface.created_by == user.id).count()
            except Exception:
                api_interfaces_count = 0
                
            try:
                scenarios_count = db.query(TestScenario).filter(TestScenario.created_by == user.id).count()
            except Exception:
                scenarios_count = 0
            
            user_stats.append({
                "user_id": user.id,
                "username": user.username,
                "full_name": user.full_name,
                "email": user.email,
                "is_admin": user.is_admin,
                "last_login": user.last_login,
                "created_at": user.created_at,
                "stats": {
                    "analysis_count": analysis_count,
                    "test_case_generation_count": test_case_generation_count,
                    "requirements_count": requirements_count,
                    "test_cases_count": test_cases_count,
                    "ui_scripts_count": ui_scripts_count,
                    "api_interfaces_count": api_interfaces_count,
                    "scenarios_count": scenarios_count
                }
            })
        
        return {
            "success": True,
            "data": {
                "users": user_stats,
                "total_users": len(user_stats)
            }
        }
        
    except Exception as e:
        logger.error(f"获取用户统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取用户统计数据失败")
